﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using easysql;
namespace Dal
{ 
    public class UserDal:BaseDal<UserModel>
    {
      //  public DepartmentDal departmentDal = DalFactory.CreateDepartmentDal();
        public UserDal()
            : base("tb_user")
        {
        }
 
        public List<Object> QueryPageVO(PageInfo<UserModel> pi,params Restrain[] restrains)
        {
            using (BaseDatabase db = dh.CreateDatabaseAndOpen())
            {
                List<Object> result = new List<Object>();
                int total = 0;
                List<UserModel> list = db.QueryByPage<UserModel>(tbname, pi.query, pi.page, pi.rows, out total,restrains);
                pi.total = total;

                String roleIdss = "";
                HashSet<object> departmentIds = new HashSet<object>();
                list.ForEach(delegate (UserModel m)
                {
                    if (!String.IsNullOrEmpty(m.roleIds))
                    {
                        if (roleIdss.Length > 0)
                        {
                            roleIdss += ",";
                        }
                        roleIdss += m.roleIds;
                    }
                    departmentIds.Add(m.departmentId);
                });

                List<RoleModel> roleList = roleIdss.Length > 0 ? db.Query<RoleModel>("tb_role", null, Restrain.Add(" id in ("+roleIdss+") ")) : new List<RoleModel>();
                List<DepartmentModel> departmentList = departmentIds.Count > 0 ? db.Query<DepartmentModel>("tb_department", null, Restrain.In("id", departmentIds.ToArray())) : new List<DepartmentModel>();
                list.ForEach(delegate (UserModel m)
                {
                    String roleNames = "";
                    String departmentName = null;
                    if (!String.IsNullOrEmpty(m.roleIds))
                    {
                        foreach (RoleModel rm in roleList)
                        {
                            if (m.roleIds.Split(',').Contains(rm.id.ToString()))
                            {
                                if (roleNames.Length > 0)
                                {
                                    roleNames += ",";
                                }
                                roleNames += rm.name;
                            }
                        }
                    }

                    var dModel = departmentList.Find(delegate (DepartmentModel dm)
                    {
                        return dm.id == m.departmentId;
                    });
                    if (dModel != null)
                    {
                        departmentName = dModel.name;
                    }

                    result.Add(new
                    {
                        id = m.id,
                        username = m.username,
                        nickname = m.nickname,
                        email = m.email,
                        sex = m.sex,
                        createTime = m.createTime,
                        roleIds = m.roleIds,
                        lastTime = m.lastTime,
                        departmentId = m.departmentId,
                        del = m.del,
                        departmentName = departmentName,
                        roleNames = roleNames
                    });

                });

                return result;
            }
        }




        public UserModel Login(string username, string password)
        {

            using(BaseDatabase db = dh.CreateDatabaseAndOpen())
            {
                var list = db.Query<UserModel>(this.tbname, null, Restrain.Eq("username", username),Restrain.Eq("del",1));
                if (list.Count == 0)
                {
                    throw new IException("用户名不存在或已被删除");
                }

                UserModel model = list[0];

                if (model.password != password)
                {
                    throw new IException("用户名或密码错误");
                }

                #region 更新lastTime为当前时间
                UserModel lastLoginModel = new UserModel();
                lastLoginModel.lastTime = DateTime.Now;
                lastLoginModel.id = model.id;
                db.Modify(tbname, lastLoginModel);
                #endregion  更新lastTime为当前时间
                return model;
            }
           
        }

       

        public void resetPassword(List<int> ids, string newPassword)
        {
            dh.Execute("update tb_user set password={0} where del=1 and id in ("+String.Join(",", ids) +")", newPassword);
        }

        ///修改密码
        public void ModifyPassword(string username, string oldPassword, string newPassword)
        {
            using (BaseDatabase db = dh.CreateDatabaseAndOpen()) {
                var list = dh.Query<UserModel>(tbname, null, Restrain.Eq("username", username),Restrain.Eq("del",1));
                if (list.Count == 0)
                {
                    throw new IException("该用户名不存在或已被删除");
                }
                var user = list[0];
                if(user.password != oldPassword)
                {
                    throw new IException("原密码错误");
                }
                int ret = db.Execute("update " + this.tbname + " set password={0} where del=1 and username={1} and password={2}", newPassword, username, oldPassword);
                if (ret == 0)
                {
                    throw new IException("修改失败");
                }

            }
           
        }
        


    }
}
